package maven.jyhs.com.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson2.JSON;
import maven.jyhs.com.dao.ApiResult;
import maven.jyhs.com.entity.User;
import maven.jyhs.com.entity.dto.UserImport;
import maven.jyhs.com.entity.dto.Users;
import maven.jyhs.com.servce.TranstfeSevrce;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@RestController
public class TranstfeConetroller {
    @Autowired
    private TranstfeSevrce transtfeService;

    @GetMapping("/transfer")
    public Map<String, Object> transferSelect(Users user) throws SQLException, ClassNotFoundException, IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "查询成功");
        user.setPage((user.getPage()-1)*user.getLimit());
        map.put("count", transtfeService.limit(user));
        map.put("data", transtfeService.getUsers(user));
        return map;

    }

    @PostMapping("/transfer")
    public ApiResult transferAdd(@Valid @RequestBody User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            StringBuilder sb = new StringBuilder();
            bindingResult.getAllErrors().stream().forEach(error -> {
                System.out.println(error.getDefaultMessage());   //输出错误信息
                sb.append(error.getDefaultMessage());
            });
            return new ApiResult(400, sb.toString(), null);
        }
        System.out.println("添加用户");
        return new ApiResult(200, "添加成功", transtfeService.add(user));
    }

    @PostMapping("/transfer/updateImage")
    public ApiResult updateMenuImage(List<MultipartFile> file) throws IOException {
        List<String> fileUrls = new ArrayList<>();
        for (MultipartFile files : file) {
            String newFileName = System.currentTimeMillis() + "_" + files.getOriginalFilename();
            files.transferTo(new File("D:/image/" + newFileName));
            fileUrls.add("http://localhost:8080/image/" + newFileName);
        }
        return new ApiResult(200, "上传成功", fileUrls);

    }

    @PutMapping("/transfer")
    public ApiResult transferUpdate(@Valid @RequestBody User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            StringBuilder sb = new StringBuilder();
            bindingResult.getAllErrors().stream().forEach(error -> {
                System.out.println(error.getDefaultMessage());   //输出错误信息
                sb.append(error.getDefaultMessage());
            });
            return new ApiResult(400, sb.toString(), null);
        }
        System.out.println("修改用户");
//        user.setId(id);
        return new ApiResult(200, "更新成功", transtfeService.update(user));
    }


    @DeleteMapping("/transfer/{id}")
    public ApiResult transferDelete(@PathVariable int id) throws IllegalAccessException {
        System.out.println("删除用户");
        return new ApiResult(200, "删除成功", transtfeService.delete(id));
    }


    @DeleteMapping("/transfer/batchDelete")
    public ApiResult transferBatchDelete(Integer[] ids) throws SQLException, IllegalAccessException {
        System.out.println("批量删除用户");
        return new ApiResult(200, "批量删除成功", transtfeService.batchDelete(Arrays.asList(ids)));

    }

    @DeleteMapping("/transfer/tset")
    public ApiResult transferTset(Integer[] ids) {
        System.out.println("测试" + ids);
        return new ApiResult(200, "测试成功", null);
    }

    @GetMapping("/export")
    public void test(HttpServletResponse response, User user) throws IOException, SQLException, ClassNotFoundException, IllegalAccessException {
        List<User> users = transtfeService.getUsersBy();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=user.xlsx");

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("用户信息");
        org.apache.poi.ss.usermodel.Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("id");
        row.createCell(1).setCellValue("name");
        row.createCell(2).setCellValue("cardnumber");
        row.createCell(3).setCellValue("phone");
        row.createCell(4).setCellValue("balance");
        row.createCell(5).setCellValue("registration");
        row.createCell(6).setCellValue("avatar");

        int rowNum = 1;
        for (User u : users) {
            Row dataRow = sheet.createRow(rowNum++);
            dataRow.createCell(0).setCellValue(u.getId());
            dataRow.createCell(1).setCellValue(u.getName());
            dataRow.createCell(2).setCellValue(u.getCardnumber());
            dataRow.createCell(3).setCellValue(u.getPhone());
            dataRow.createCell(4).setCellValue(u.getBalance());
            dataRow.createCell(5).setCellValue(u.getRegistration());
            dataRow.createCell(6).setCellValue(u.getAvatar());

        }
        workbook.write(response.getOutputStream());
        workbook.close();
        return;
    }

    @PostMapping("/import")
    public ApiResult importExcel(@RequestParam("file")MultipartFile file) throws IOException, SQLException, ClassNotFoundException, IllegalAccessException {
        String fileName = file.getOriginalFilename();
        String flag = "\\.([a-zA-Z0-9]+)$";
        final Integer[] result = {0};
        Pattern pattern = Pattern.compile(flag);
        Matcher matcher = pattern.matcher(fileName != null ? fileName : "");
        if (matcher.find()) {
            String ext = matcher.group(1);
            if ("xls".equals(ext) || "xlsx".equals(ext)) {
                EasyExcel.read(file.getInputStream(), UserImport.class, new ReadListener<UserImport>() {
                    @Override
                    public void invoke(UserImport userImport, AnalysisContext analysisContext) {
                        User user = new User(
                                0,
                                userImport.getName(),
                                userImport.getCardnumber(),
                                userImport.getRegistration(),
                                userImport.getBalance(),
                                userImport.getPhone()
                                , userImport.getAvatar(),
                                null);
                        result[0] = transtfeService.add(user);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        System.out.println("所有数据解析完成，一共" + result[0] + "条数据");

                    }

                }).sheet().doRead();
                return new ApiResult(200, "导入成功", result[0]);

            }
        }
      return  new ApiResult(400, "导入失败", null);
    }

}

